package servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.PageBean;
import pojo.Product;
import service.ProductService;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IndexServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method=request.getParameter("method");
		if(method.equals("showProductByType")) {
			showProductByType(request,response);
		}else if(method.equals("findProductById")) {
			findProductById(request,response);
		}
	}
	private void findProductById(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String pid=request.getParameter("pid");
		ProductService pservice=new ProductService();
		Product p = pservice.getProduct(pid);
		request.setAttribute("p", p);
		try {
			request.getRequestDispatcher("detail.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void showProductByType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int pageSize,currentPage;
		if(request.getParameter("pageSize")==null) {
			pageSize=8;
		}else {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		if(request.getParameter("currentPage")==null) {
			currentPage=1;
		}else {
			currentPage = Integer.parseInt(request.getParameter("currentPage"));
		}
		ProductService ps = new ProductService();
		PageBean<Product> pb1=ps.showAllByType(currentPage, pageSize, "电脑专区");
		PageBean<Product> pb2=ps.showAllByType(currentPage, pageSize, "厨卫系列");
		PageBean<Product> pb3=ps.showAllByType(currentPage, pageSize, "电视机系列");
		PageBean<Product> pb4=ps.showAllByType(currentPage, pageSize, "洗衣机系列");
		request.setAttribute("pb1", pb1);
		request.setAttribute("pb2", pb2);
		request.setAttribute("pb3", pb3);
		request.setAttribute("pb4", pb4);
	}

}
